package com.lehecai.core.search.api;

import com.lehecai.core.bean.PairValue;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class SearchApiRequestGet {

    /**
     * 分页信息，参考mysql的limit
     */
	private int offset = 0;
	private int limit = SearchApiConstant.API_REQUEST_PAGESIZE_DEFAULT;

    /**
     * 需要返回的字段
     */
	private String[] field;

    private List<PairValue<String, Boolean>> orderList = new ArrayList<PairValue<String, Boolean>>();

    protected void addOrder(String field, boolean desc) {
        orderList.add(new PairValue<String, Boolean>(field, desc));
    }

    public void addOrderASC(String field) {
        this.addOrder(field, false);
    }

    public void addOrderDESC(String field) {
        this.addOrder(field, true);
    }

    public JSON toJSON() {
        JSONObject jsonObject = new JSONObject();

        jsonObject.put(SearchApiConstant.API_PARAMETER_GET_OFFSET, this.offset);
        jsonObject.put(SearchApiConstant.API_PARAMETER_GET_LIMIT, this.limit);

        JSONArray fieldArray = new JSONArray();
        for (String f : this.field) {
            fieldArray.add(f);
        }
        jsonObject.put(SearchApiConstant.API_PARAMETER_GET_FIELD, fieldArray);

        JSONArray orderArray = new JSONArray();
        for (PairValue<String, Boolean> pairValue : this.orderList) {
            JSONObject orderItemObject = new JSONObject();
            orderItemObject.put(SearchApiConstant.API_PARAMETER_GET_ORDER_NAME, pairValue.getLeft());
            orderItemObject.put(SearchApiConstant.API_PARAMETER_GET_ORDER_DESC, pairValue.getRight());

            orderArray.add(orderItemObject);
        }
        jsonObject.put(SearchApiConstant.API_PARAMETER_GET_ORDER, orderArray);
        
        return jsonObject;
    }


    public int getOffset() {
        return offset;
    }

    public void setOffset(int offset) {
        this.offset = offset;
    }

    public String[] getField() {
        return field;
    }

    public void setField(String[] field) {
        this.field = field;
    }

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }
}
